package domain;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "event")
public class Event extends PersistentEntity {
	@OneToOne(fetch=FetchType.EAGER)
	private User creator;
	
	private String name;
	private String location;
	private Date date;
	@Column(length=10000)
	private String description;
	
	@ManyToMany
	private List<User> usersInvited;
	
	//hibernate
	public Event() {
	}
	
	public Event(User creator, String name, Date startDate, String location, String description) {
		this.creator = creator;
		this.name = name;
		this.date = startDate;
		this.location = location;
		this.description = description.replace("\n", "<br />");
		this.usersInvited = new ArrayList<User>();
	}

	public User getCreator() {
		return creator;
	}

	public void setCreator(User creator) {
		this.creator = creator;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public void setUsersInvited(List<User> usersInvited) {
		if (usersInvited != null) {
			this.usersInvited = usersInvited;
		}
	}
	
	public void addSearchProfiles(List<SearchResultList> profiles) {
		if (profiles != null) {
			for (SearchResultList profile: profiles) {
				for (SearchResultItem item: profile.getResults()) {
					User u = item.getUser();
					if (!usersInvited.contains(u)) {
						this.usersInvited.add(u);
					}
				}
			}
		}
	}

	public List<User> getUsersInvited() {
		return usersInvited;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Event other = (Event) obj;
		return other.getId() == this.getId();
	}

	@Override
	public int hashCode() {
		return this.getId();
	}
	
	public String getFormattedDate() {
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy - HH:mm");
		return df.format(this.getDate());
	}
	
	@Override
	public String toString() {
		return "<h2>" + this.getName() + "</h2>" +
				"<b>Creado por: </b>" + this.getCreator().getName() + " " + this.getCreator().getLastName() + "</li><br />" +
				"<b>Ubicación: </b>" + this.getLocation() + "</li><br />" +
				"<b>Fecha de inicio: </b>" + this.getFormattedDate() + "</li><br />" +
				"<p>" +
				this.getDescription() +
				"</p>";
	}
}